<template>
    <div style="padding: 20px;">
        <div class="overview-title">
            <el-icon>
                <Postcard />
            </el-icon>
            <div>
                热度变化分析
            </div>
        </div>
        <el-row justify='center'>
            <el-col :span="24">
                <div id="heat-line" style="width: 90%; height: 410px;"></div>
            </el-col>
        </el-row>
        <el-row justify='center'>
            <el-col :span="12">
                <div id="fanclub-line" style="width: 100%; height: 360px;"></div>
            </el-col>
            <el-col :span="12">
                <div id="online-line" style="width: 100%; height: 360px;"></div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch, defineProps } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Postcard } from '@element-plus/icons-vue';

import * as echarts from 'echarts';

const { appContext } = getCurrentInstance();
const HOST_URL = appContext.config.globalProperties.$HOST_URL;
const props = defineProps({
    room_id: String,
    analyzed_date: String
});

let heatData = ref([]);
let fanClub = ref([]);
let online = ref([]);

let heatLine = null;
let fanClubLine = null;
let onlineLine = null;
const initChart = () => {
    heatLine = echarts.init(document.getElementById('heat-line'));
    fanClubLine = echarts.init(document.getElementById('fanclub-line'));
    onlineLine = echarts.init(document.getElementById('online-line'));
};

const fetchHeatDateList = async (roomId, roomDate) => {
    try {
        const response = await axios.get(`${HOST_URL}/chart/room/hour/heat_list`, { params: { room_id: roomId, analyze_time: roomDate } });
        heatData.value = response.data;
    } catch (error) {
        ElMessage.error('后端请求失败');
        console.error('请求失败:', error);
    }
};

const fetchFanClubLineList = async (roomId, roomDate) => {
    try {
        const response = await axios.get(`${HOST_URL}/chart/room/hour/fanclub_list`, { params: { room_id: roomId, analyze_time: roomDate } });
        fanClub.value = response.data;
    } catch (error) {
        ElMessage.error('后端请求失败');
        console.error('请求失败:', error);
    }
};

const fetchOnlineList = async (roomId, roomDate) => {
    try {
        const response = await axios.get(`${HOST_URL}/chart/room/hour/online_list`, { params: { room_id: roomId, analyze_time: roomDate } });
        online.value = response.data;
    } catch (error) {
        ElMessage.error('后端请求失败');
        console.error('请求失败:', error);
    }
};


const GetHeatLine = () => {
    const keyMap = {
        ChatMessage: '聊天消息',
        GiftMessage: '礼物消息',
        LikeMessage: '点赞消息',
        MemberMessage: '进入消息',
        SocialMessage: '关注消息'
    };

    const types = Object.keys(keyMap);
    const datasetWithFilters = [];
    const seriesList = [];

    echarts.util.each(types, function (type) {
        const datasetId = 'dataset_' + type;
        datasetWithFilters.push({
            id: datasetId,
            fromDatasetId: 'dataset_raw',
            transform: {
                type: 'filter',
                config: {
                    and: [{ dimension: 'type', '=': type }]
                }
            }
        });
        seriesList.push({
            type: 'line',
            datasetId: datasetId,
            showSymbol: false,
            name: keyMap[type], // 使用中文名称
            endLabel: {
                show: true,
                formatter: function (params) {
                    return `${params.value[0]}: ${params.value[2]} (${keyMap[params.value[1]]
                        })`; // 中文标签
                }
            },
            labelLayout: {
                moveOverlap: 'shiftY'
            },
            emphasis: {
                focus: 'series'
            },
            encode: {
                x: 'hour',
                y: 'value',
                label: ['type', 'value'],
                itemName: 'hour',
                tooltip: ['value']
            }
        });
    });

    const option = {
        animationDuration: 8000,
        dataset: [
            {
                id: 'dataset_raw',
                source: heatData.value
            },
            ...datasetWithFilters
        ],
        // title: {
        //     text: ''
        // },
        tooltip: {
            order: 'valueDesc',
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            nameLocation: 'middle'
        },
        yAxis: {
            name: '消息数量'
        },
        grid: {
            right: 140
        },
        series: seriesList
    };

    option && heatLine.setOption(option);
};

const GetFanClubHeatLine = () => {
    const keyMap = {
        FansclubMessage: '粉丝团新增',
    };

    const types = Object.keys(keyMap);
    const datasetWithFilters = [];
    const seriesList = [];

    echarts.util.each(types, function (type) {
        const datasetId = 'dataset_' + type;
        datasetWithFilters.push({
            id: datasetId,
            fromDatasetId: 'dataset_raw',
            transform: {
                type: 'filter',
                config: {
                    and: [{ dimension: 'type', '=': type }]
                }
            }
        });
        seriesList.push({
            type: 'line',
            datasetId: datasetId,
            showSymbol: false,
            name: keyMap[type], // 使用中文名称
            endLabel: {
                show: true,
                formatter: function (params) {
                    return `${params.value[0]}: ${params.value[2]} (${keyMap[params.value[1]]
                        })`; // 中文标签
                }
            },
            labelLayout: {
                moveOverlap: 'shiftY'
            },
            emphasis: {
                focus: 'series'
            },
            encode: {
                x: 'hour',
                y: 'value',
                label: ['type', 'value'],
                itemName: 'hour',
                tooltip: ['value']
            }
        });
    });

    const option = {
        animationDuration: 8000,
        dataset: [
            {
                id: 'dataset_raw',
                source: fanClub.value
            },
            ...datasetWithFilters
        ],
        // title: {
        //     text: ''
        // },
        tooltip: {
            order: 'valueDesc',
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            nameLocation: 'middle'
        },
        yAxis: {
            name: '粉丝团新增数'
        },
        grid: {
            right: 140
        },
        series: seriesList
    };

    option && fanClubLine.setOption(option);
};

const GetOnlineLine = () => {
    const keyMap = {
        RoomUserSeqMessage: '在线人数',
    };

    const types = Object.keys(keyMap);
    const datasetWithFilters = [];
    const seriesList = [];

    echarts.util.each(types, function (type) {
        const datasetId = 'dataset_' + type;
        datasetWithFilters.push({
            id: datasetId,
            fromDatasetId: 'dataset_raw',
            transform: {
                type: 'filter',
                config: {
                    and: [{ dimension: 'type', '=': type }]
                }
            }
        });
        seriesList.push({
            type: 'line',
            datasetId: datasetId,
            showSymbol: false,
            name: keyMap[type], // 使用中文名称
            endLabel: {
                show: true,
                formatter: function (params) {
                    return `${params.value[0]}: ${params.value[2]} (${keyMap[params.value[1]]
                        })`; // 中文标签
                }
            },
            labelLayout: {
                moveOverlap: 'shiftY'
            },
            emphasis: {
                focus: 'series'
            },
            encode: {
                x: 'hour',
                y: 'value',
                label: ['type', 'value'],
                itemName: 'hour',
                tooltip: ['value']
            }
        });
    });

    const option = {
        animationDuration: 8000,
        dataset: [
            {
                id: 'dataset_raw',
                source: online.value
            },
            ...datasetWithFilters
        ],
        // title: {
        //     text: ''
        // },
        tooltip: {
            order: 'valueDesc',
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            nameLocation: 'middle'
        },
        yAxis: {
            name: '人数'
        },
        grid: {
            right: 140
        },
        series: seriesList
    };

    option && onlineLine.setOption(option);
};

onMounted(() => {
    initChart();
    fetchHeatDateList(props.room_id, props.analyzed_date);
    fetchFanClubLineList(props.room_id, props.analyzed_date);
    fetchOnlineList(props.room_id, props.analyzed_date);
})

// 监听父组件传递的参数变化
watch(() => props.analyzed_date, (newDate) => {
    if (newDate) {
        fetchHeatDateList(props.room_id, newDate);
        fetchFanClubLineList(props.room_id, newDate);
        fetchOnlineList(props.room_id, newDate);
    }
});

// 监听 heatData 的变化，当 heatData.value 更新后调用 GetHeatLine
watch(heatData, (newHeatData) => {
    if (newHeatData) {
        GetHeatLine();
    }
});

watch(fanClub, (newFanClubData) => {
    if (newFanClubData) {
        GetFanClubHeatLine();
    }
});

watch(online, (newOnlineData) => {
    if (newOnlineData) {
        GetOnlineLine();
    }
});

</script>

<style scoped lang="scss">
.overview-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    margin-bottom: 24px;
    position: relative;

    .el-icon {
        margin-right: 8px;
        font-size: 24px;
    }

    &::after {
        content: '';
        display: block;
        width: 142px;
        height: 1px;
        background-color: rgb(168, 135, 135);
        position: absolute;
        bottom: -20px;
        /* 调整与文字的距离 */
        left: 0;
    }
}
</style>